﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace YeaTrip.Common
{
    // XML序列化工具类
    public class XmlSerializeHelper
    {
        /// <summary>
        /// 返回obj对象序列化后的Xml文本
        /// </summary>
        public static string XmlSerialize(object obj)
        {
            try
            {
                if (obj == null)
                    return null;

                using (MemoryStream ms = new MemoryStream(1024))
                {
                    XmlSerializer xs = new XmlSerializer(obj.GetType());
                    xs.Serialize(ms, obj);
                    ms.Flush();

                    ms.Seek(0, SeekOrigin.Begin);
                    XmlTextReader xtr = new XmlTextReader(ms);
                    xtr.WhitespaceHandling = WhitespaceHandling.None;
                    xtr.Read();
                    while (xtr.NodeType == XmlNodeType.XmlDeclaration)
                        xtr.Read();

                    //return xtr.ReadOuterXml();
                    string str = xtr.Name;
                    return "<" + str + ">" + xtr.ReadInnerXml() + "</" + str + ">";
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
